package com.purong.purong.widget;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

public class ExtGridLayoutManager extends GridLayoutManager {
    // RecyclerView高度随Item自适应
    private int verPadding=0;
    private boolean headAndBottom=false;


    @Override
    public boolean canScrollVertically() {
        return false;
    }

    public ExtGridLayoutManager(Context context, int spanCount) {
        super(context,spanCount);
    }
    public ExtGridLayoutManager(Context context, int spanCount, int verPadding) {
        super(context,spanCount);
        this.verPadding=verPadding;
    }
    public ExtGridLayoutManager(Context context, int spanCount, int verPadding, boolean headAndBottom) {
        super(context,spanCount);
        this.verPadding=verPadding;
        this.headAndBottom=headAndBottom;
    }
    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, final int widthSpec, final int heightSpec) {
        int itemCount = state.getItemCount();
        int spnCount = getSpanCount();
        int i = itemCount % spnCount;
        int lineCount = itemCount / spnCount;

        if (i > 0 ) {
            lineCount += 1;
        }
        if (itemCount < spnCount) {
            lineCount = 1;
        }
        if (lineCount < 1) {
            lineCount = 1;
        }
//        Log.e("zwj","........lineCount="+lineCount);
        if (itemCount==0){

            setMeasuredDimension(0, 0);
        }else {
            try{
                View view = recycler.getViewForPosition(0);
                if(view != null){
                    measureChild(view, widthSpec, heightSpec);
                    int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                    int measuredHeight = view.getMeasuredHeight();
                    if (headAndBottom){
                        setMeasuredDimension(measuredWidth,measuredHeight*lineCount+ verPadding*(lineCount+1));
                    }else {
                        setMeasuredDimension(measuredWidth,measuredHeight*lineCount+ verPadding*(lineCount-1));

                    }
                }
            }catch (Exception e){
                Log.e("zwj","....e="+e.toString());
                setMeasuredDimension(0, 0);
            }

        }


    }

}